angular.module('baisonPatch', ['baisonDb', 'baisonService'])
        //补丁包列表数据获取
        .factory('PatchList', ['$rootScope', 'apiService', function ($rootScope, apiService) {
                return function () {
                    var param = {};
                    param['device'] = baison_app.api.deviceId;
                    param['shop_code'] = $rootScope.current_shop.ShopCode;
                    return apiService('patch/patch/get_list', param);
                };
            }])
        //补丁包下载
        .factory('PatchDownload', ['$location', '$rootScope', '$q', 'PatchInstall', 'dbTrans', '$http', 'timeStamp2String', 'apiService','dbDelete', function ($location, $rootScope, $q, PatchInstall, dbTrans, $http, timeStamp2String, apiService,dbDelete) {
                //@TODO 下载路径IP地址需要从配置文件读取
                var configData = $api.getStorage('configData');
                var pathurl;
                if ((configData.api_url).indexOf(":", 10) == -1) {
                    pathurl = (configData.api_url).substring(0, (configData.api_url).indexOf("/", 10)) + "/patch/";
                } else if ((configData.api_url).indexOf("/", 30) != -1) {
                    pathurl = (configData.api_url).substring(0, (configData.api_url).indexOf("/", 30)) + "/manage/web/patch/";
                }
                var base_url = pathurl;
                var sys_type = '';//系统类型 pc 非pc
                try {
                    var os = nodeRequire('os');
                    switch (os.type()) {
                        case "Windows_NT":
                        case "Linux":
                        case "Darwin":
                            sys_type = 'pc';
                    }
                } catch (e) {
                    sys_type = '';
                }
                var load_deferred = $q.defer();
                var load_promise = load_deferred.promise;
                var install_deferred = $q.defer();
                var install_promise = install_deferred.promise;
                var install_deferred_single = {};
                var install_promise_single = {};
                var patchtype = '';
                var patch_file_num = 1;
                var is_paser = 0;//是否解压



                //获取下载地址
                var get_down_adress = function (patch) {
                    return patch.patch_url;
                };
                //获取pad下载状态
                var patch_query_status = function (id, callback) {
                    baison_app.manager.query({
                        ids: [id]
                    }, function (ret, err) {
                        if (ret.data) {
                            if (ret.data[0].status < 3) {
                                patch_query_status(id, callback);
                            } else {
                                callback(ret.data[0].status);
                            }
                        }
                    });
                };
                //删除 pad manage 信息
                var del_manage_patch_info = function (patch, id, callback) {
                    baison_app.manager.query({
                        ids: [id]
                    }, function (ret, err) {
                        var data = ret.data;
                        if (data) {
                            baison_app.manager.remove({
                                ids: [id]
                            }, function (ret, err) {
                                var url = get_down_adress(patch);
                                baison_app.manager.enqueue({
                                    url: url,
                                    savePath: 'fs://' + patch.basename,
                                    cache: false,
                                    allowResume: false,
                                    title: patch.basename + $rootScope.language.TIPS_SET_SERVICE_PACK,
                                    uncompress: true,
                                    networkTypes: 'all',
                                    mimeType: 'application/zip',
                                }, function (ret, err) {
                                    if (ret.id) {
                                        patch_query_status(id, callback);
                                    }
                                });
                            });
                        }
                    });
                };

                //移动设备补丁包下载逻辑
                var patch_download_logic = function (patch) {
                    var url = get_down_adress(patch);
                    baison_app.manager.enqueue({
                        url: url,
                        savePath: 'fs://' + patch.basename,
                        cache: false,
                        allowResume: false,
                        title: patch.basename + $rootScope.language.TIPS_SET_SERVICE_PACK,
                        uncompress: true,
                        networkTypes: 'all',
                        mimeType: 'application/zip',
                    }, function (ret, err) {
                        if (ret.id) {
                            //回写下载接口
                            var fdids = ret.id;
                            patch_query_status(fdids, function (status) {
                                if (status == 3) {
                                    var data = {};
                                    data['patch_code'] = patch['patch_code'];
                                    data['fd_ids'] = ret.id;
                                    data['patch_status'] = 'TIP_INDEX_UNFIXED';
                                    var prompt = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
                                    writeback_patchlog(data, prompt, '');
                                } else if (status == 4) {
                                    del_manage_patch_info(patch, ret.id, function (status) {
                                        if (status == 3) {
                                            var data = {};
                                            data['patch_code'] = patch['patch_code'];
                                            data['fd_ids'] = ret.id;
                                            data['patch_status'] = 'TIP_INDEX_UNFIXED';
                                            var prompt = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
                                            writeback_patchlog(data, prompt, '');
                                        }
                                    });
                                }
                            });
                        }
                    });
                };

                //安装成功后 删除 pad manage列表信息
                var del_manage_patchinfo = function (id) {
                    if (id != '') {
                        baison_app.manager.query({
                            ids: [id]
                        }, function (ret, err) {
                            var data = ret.data;
                            if (data) {
                                baison_app.manager.remove({
                                    ids: [id]
                                }, function (ret, err) {

                                });
                            }
                        });
                    }
                };
                //pc判断安装包的大小
                var is_check_patch_size = function (path, patch) {
                    var fs = nodeRequire('fs');
                    var install_size_deferred = $q.defer();
                    var install_size_promise = install_size_deferred.promise;
                    fs.stat(path, function (err, stats) {
                        if (err) {
                            install_size_deferred.resolve(0);
                        } else {
                            if (patch.patch_size_bp - stats.size > parseInt(stats.size * 0.1) || stats.size == 0) {
                                install_size_deferred.resolve(0);
                            } else {
                                install_size_deferred.resolve(1);
                            }
                        }
                    });
                    return install_size_promise;
                };
                //pc机补丁包下载逻辑
                var pc_patch_download_logic = function (patch) {
                    var url = get_down_adress(patch);
                    var http = nodeRequire('http');
                    var fs = nodeRequire('fs');
                    var unzip = nodeRequire('unzip');
                    var urlModel = nodeRequire('url');
                    var path = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.basename;
                    var dirpath = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.patch_code;
                    fs.exists(baison_app.api.fsDir + '\\' + 'download', function (exist) {
                        if (!exist) {
                            fs.mkdir(baison_app.api.fsDir + '\\' + 'download');
                        }
                    });

                    var url_info = urlModel.parse(url);
                    http.get(url, function (res) {
                        if (res.statusCode == 302 || res.statusCode == 301) {
                            http.get(res.headers.location, function (res300) {
                                download_handler(res300);
                            });
                        } else if (res.statusCode == 200) {
                            download_handler(res);
                        } else {
//                            console.log(res.statusCode);
                        }
                    });

                    var download_handler = function (res) {
                        var file = fs.createWriteStream(path);
                        res.pipe(file);
                        res.on('end', function () {
                            baison_app.fs.exist({
                                path: path
                            }, function (ret, err) {
                                var data = {};
                                if (ret.exist) {
                                    is_check_patch_size(path, patch).then(function (ret) {
                                        if (ret == 0) {
                                            data['patch_code'] = patch['patch_code'];
                                            data['fd_ids'] = '';
                                            data['patch_status'] = 'TIP_INDEX_NOT_DOWNLOAD';
                                            var prompt = $rootScope.language.TIPS_NO_NETWORK_NO_DOWNLOAD;//$rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
                                            writeback_patchlog(data, prompt, '');
                                        } else if (ret == 1) {
                                            data['patch_code'] = patch['patch_code'];
                                            data['fd_ids'] = '';
                                            data['patch_status'] = 'TIP_INDEX_UNFIXED';
                                            var prompt = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
                                            writeback_patchlog(data, prompt, '');
                                        }
                                    });
                                } else {
                                    setTimeout(function () {
                                        data['patch_code'] = patch['patch_code'];
                                        data['fd_ids'] = '';
                                        data['patch_status'] = 'TIP_INDEX_UNFIXED';
                                        var prompt = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
                                        writeback_patchlog(data, prompt, '');
                                    }, 1000);
                                }
                            });
                        });
                    };

                };



                //解压文件
                var unzip_file_zip = function (patch) {
                    $rootScope.progressTips = $rootScope.language.TIP_FLIE_UNZIP_START + patch.basename;
                    var path = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.basename;
                    var dirpath = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.patch_code;
                    var unzip = nodeRequire('unzip');
                    var fs = nodeRequire('fs');
                    patch.son = 0; //子文件数量
                    baison_app.fs.exist({
                        path: path
                    }, function (ret, err) {
                        if (ret.exist) {
                            is_check_patch_size(path, patch).then(function (ret) {
                                if (ret == 0) {
//                                    console.log('解压文件大小校验不通过!!!');
                                    data['patch_code'] = patch['patch_code'];
		                            data['fd_ids'] = '';
		                            data['patch_status'] = 'TIP_INDEX_NOT_DOWNLOAD';
		                            baison_app.api.toast({msg:$rootScope.language.TIPS_DOWN_FILES_SIZE_ERROR});
		                            var prompt = $rootScope.language.TIPS_NO_NETWORK_NO_DOWNLOAD;//$rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
		                            writeback_patchlog(data, prompt, 0);
                                } else if (ret == 1) {
                                    var rs = fs.createReadStream(path);
                                    rs.pipe(unzip.Parse()).on('entry', function (entry) {
                                        var fileName = dirpath + '\\' + entry.path;
                                        var type = entry.type;
                                        if (type == 'File') {
                                            fs.exists(dirpath, function (exist) {
                                                if (!exist) {
//                                                    console.log('目录不存在先创建目录：', dirpath);
                                                    fs.mkdir(dirpath, '0777', function (err) {
                                                        if (!err) {
                                                            fs.open(fileName, 'w', function (error, fd) {
                                                                if (!error) {
                                                                    entry.pipe(fs.createWriteStream(fileName));
                                                                    entry.on('end', function (err) {
//                                                                        console.log('文件解压成功：', fileName);
                                                                        $rootScope.progressTips = $rootScope.language.TIP_FLIE_UNZIP_FINISH + fileName;
                                                                        patch.son++;
                                                                    });
                                                                } else {
                                                                    //console.log('文件竟然创建失败了!!!')
                                                                    //install_deferred_single.resolve({data:'error'}); 
                                                                }
                                                            });
                                                        } else {
//                                                            console.log('目录创建失败!!!', dirpath);
                                                        }
                                                    });
                                                } else {
                                                    fs.open(fileName, 'w', function (error, fd) {
                                                        if (!error) {
                                                            entry.pipe(fs.createWriteStream(fileName));
                                                            entry.on('end', function () {
//                                                                console.log('文件解压成功：', fileName);
                                                                $rootScope.progressTips = $rootScope.language.TIP_FLIE_UNZIP_FINISH + fileName;
                                                                patch.son++;
                                                                 //muli_tran_install('', patch);
                                                            });
                                                        } else {
                                                            //console.log('文件竟然创建失败了!!!')
                                                            //install_deferred_single.resolve({data:'error'}); 
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    });
                                    rs.on('end', function () {
//                                        console.log('文件解压流程结束, 执行批量安装流程');
                                        setTimeout(function () {
                                            muli_tran_install('', patch);
                                        }, 1000);
                                    });
                                }
                            });
                        } else {
//                            console.log('下载的压缩文件不存在!', path);
                            muli_tran_install('', patch);
                            //install_deferred_single.resolve({data:'error'});
                        }
                    });

                };
                //补丁包下载
                var patch_download = function (patch) {
                    load_deferred = $q.defer();
                    load_promise = load_deferred.promise;
                    var patch_path = '';
                    if (sys_type != 'pc') {
                        patch_path = 'fs://' + patch.patch_code;
                    } else {
                        patch_path = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.basename;
                    }
                    baison_app.fs.exist({
                        path: patch_path
                    }, function (ret, err) {
                        if (!ret.exist) {
                            if (sys_type == 'pc') {
                                //console.log(patch_path);
                                pc_patch_download_logic(patch);
                            } else {
                                patch_download_logic(patch);
                            }
                        } else {
                            if (sys_type == 'pc') {
                                var data = {};
                                is_check_patch_size(patch_path, patch).then(function (ret) {
                                    if (ret == 0) {
                                        //console.log('00000000000000');
                                        pc_patch_download_logic(patch);
                                    } else {
                                        data['patch_code'] = patch['patch_code'];
                                        data['fd_ids'] = '';
                                        data['patch_status'] = 'TIP_INDEX_UNFIXED';
                                        var prompt = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
                                        writeback_patchlog(data, prompt, '');
                                    }

                                });


                            } else {
                                var data = {};
                                data['patch_code'] = patch['patch_code'];
                                data['fd_ids'] = '';
                                data['patch_status'] = 'TIP_INDEX_UNFIXED';
                                var prompt = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
                                writeback_patchlog(data, prompt, '');
                            }


                        }
                    });
                    return load_promise;
                };
                
                //pad版文件类型数据包安装
                var file_install_pad = function(patch,patchname){
                    var fs = baison_app.fs;
                    var file_name_arr = [];
					var patchname=patchname;
					var patch_code =patch.patch_code; 
                    var path = 'file://' + baison_app.api.fsDir + '/'+ patch.patch_code;
					var newpath = 'file://' + baison_app.api.fsDir + '/'+ 'barImage';
                    fs.readDir({
                        path:path
                    }, function(ret, err){        
                        if( ret.status ){
                            file_name_arr = ret.data;
                        }else{
                            var data = {};
                            data['patch_code'] = patch_code;
                            data['patch_status'] = 'TIP_INDEX_FIXED';
                            data['fd_ids'] = '';
                            var prompt = $rootScope.language.TIP_PATCH_FIXED;
                            //最后一个安装成功
                            $rootScope.progressTips = patchname + $rootScope.language.TIP_INSTALL_FINISH;
                            writeback_patchlog(data, prompt, -1);	
                        }
                    });
                    //
                    fs.exist({
                        path: newpath
                    }, function (ret, err) {
                        if (!ret.exist) {
                             //创建文件夹
                            fs.createDir({
                                path: newpath
                            }, function(ret, err){  
                                if( ret.status ){
                                    //拷贝文件
                                    copyTo();
                                }else{
                                    baison_app.api.alert({msg:$rootScope.language.TIP_CREATE_DIR_FAIL});
                                }
                            });
                        }else{
                            //拷贝文件
                            copyTo();
                        }
                    });
					var copyToLogic = function(path,n,newpath,i,len){
						fs.copyTo({
							oldPath: path+'/'+n,
							newPath: newpath
						}, function(ret, err){ 
							if( ret.status ){
								
								if(i >= len -1){
									var data = {};
									data['patch_code'] = patch_code;
									data['patch_status'] = 'TIP_INDEX_FIXED';
									data['fd_ids'] = '';
									var prompt = $rootScope.language.TIP_PATCH_FIXED;
									//最后一个安装成功
									$rootScope.progressTips = patchname + $rootScope.language.TIP_INSTALL_FINISH;
									writeback_patchlog(data, prompt, -1);	
								}
							}else{
								if(err.code == 7){ //存在同名项目 不拷贝 删除重新拷贝
									fs.remove({
										path: newpath +'/'+n
									}, function(ret, err){ 
										if( ret.status ){
											copyToLogic(path,n,newpath,i,len);
										}else{
											
										}
									});
									
								}
							}
						});
					};
                    var copyTo = function(){
						var len = file_name_arr.length; 
                        file_name_arr.forEach(function(n,i){
							
							copyToLogic(path,n,newpath,i,len);
                        });
                    };
                };
                //pc版文件类型数据包安装
                var file_install_pc = function(patch,patchname){
                    var fs = nodeRequire('fs');
                    var stat = fs.stat;
					var patch_code = patch.patch_code;
					var patchname = patchname;
					
                    /*
                    * 复制目录中的所有文件包括子目录
                    * @param{ String } 需要复制的目录
                    * @param{ String } 复制到指定的目录
                    */
                    var copy = function( src, dst ){
                        // 读取目录中的所有文件/目录
                        fs.readdir( src, function( err, paths ){
                            if( err ){
                                throw err;
                            }
							var len = paths.length;
                            paths.forEach(function( path,i ){
                                var _src = src + '/' + path,
                                    _dst = dst + '/' + path,
                                    readable, writable;      
                                stat( _src, function( err, st ){
                                    if( err ){
                                        throw err;
                                    }
                                    // 判断是否为文件
                                    if( st.isFile() ){
                                        // 创建读取流
                                        readable = fs.createReadStream( _src );
                                        // 创建写入流
                                        writable = fs.createWriteStream( _dst );  
                                        // 通过管道来传输流
                                        readable.pipe( writable );
										if(i >= len -1){
											var data = {};
											data['patch_code'] = patch_code;
											data['patch_status'] = 'TIP_INDEX_FIXED';
											data['fd_ids'] = '';
											var prompt = $rootScope.language.TIP_PATCH_FIXED;
											//最后一个安装成功
											$rootScope.progressTips = patchname + $rootScope.language.TIP_INSTALL_FINISH;
											writeback_patchlog(data, prompt, -1);	
										}
                                    }
                                    // 如果是目录则递归调用自身
                                    else if( st.isDirectory() ){
                                        exists( _src, _dst, copy );
                                    }
                                });
                            });
                        });
                    };
                    // 在复制目录前需要判断该目录是否存在，不存在需要先创建目录
                    var exists = function( src, dst, callback ){
                        fs.exists( dst, function( exists ){
                            // 已存在
                            if( exists ){
                                callback( src, dst );
                            }
                            // 不存在
                            else{
                                fs.mkdir( dst, function(){
                                    callback( src, dst );
                                });
                            }
                        });
                    };
                    var src = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.patch_code;
                    var dst = baison_app.api.fsDir + '\\' + 'barImage';
                    // 复制目录
                    exists( src, dst, copy );    
                };
                //文件类型数据包安装
                var file_install = function(patch,patchname){
                    if (sys_type == 'pc') {
                        file_install_pc(patch,patchname);
                        return;
                    }
                    file_install_pad(patch,patchname);
                };
                //多事务安装
                var muli_tran_install = function (i, patch) {
                	
                    var patchname = '';
                    var patchtype = '';
                    patchname = 'patch_data' + i + '.json';
                    if (patch.basename[2] == '1') {//sku数据包
                        if (i == '') {
                            i = 0;
                        }
                        patchname = 'patch_data' + i + '.json';
                        patchtype = 'sku';
                    } else if (patch.basename[2] == '2') {//促销包
                        if (i == '') {
                            patchname = 'patch_data.json';
                        }
                        patchtype = 'promotion';
                    } else if (patch.basename[2] == '3') {//sku档案包
                        if (i == '') {
                            i = 0;
                        }
                        patchname = 'patch_data' + i + '.json';
                        patchtype = 'skufile';
                    } else if (patch.basename[2] == '4') { //调价包
                        if (i == '') {
                            i = 0;
                        }
                        patchname = 'patch_data' + i + '.json';
                        patchtype = 'adjust_price';
                    } else if (patch.basename[2] == '5') { //定价包
                        if (i == '') {
                            i = 0;
                        }
                        patchname = 'patch_data' + i + '.json';
                        patchtype = 'goods_price';
                    } else if(patch.basename[2] == '6'){ //文件类型数据包
						patchname = 'patch_data.json';
                        file_install(patch,patchname);
                        return;
                    } else if (patch.basename[2] == '7') { //商品条码数据包
                        if (i == '') {
                            i = 0;
                        }
                        patchname = 'patch_data' + i + '.json';
                        patchtype = 'goods_barcode';
                    } else {
                        if (i == '') {
                            patchname = 'patch_data.json';
                        }
                        patchtype = 'other'; //基础档案包
                    }

                    install_deal(patchtype, patch, patchname, i).then(function (ret) {
                        //单个数据包安装结果
                        if (ret.data == 'error') {
                            //安装失败
                            var data = {};
                            data['patch_code'] = patch['patch_code'];
                            data['patch_status'] = 'TIP_INDEX_UNFIXED';
                            data['fd_ids'] = '';
                            var prompt = $rootScope.language.TIP_PATCH_FIXED;
                            //安装失败了, 广播
                            $rootScope.progressTips = patchname + $rootScope.language.TIP_INSTALL_FAIL;
                            writeback_patchlog(data, prompt, -1);
                        } else {
                            i++;
                            //如果i为最后一个子数据包，或者只有一个子数据包，则结束安装
                            if (patch.son == i || patch.son == 1) {
                                var data = {};
                                data['patch_code'] = patch['patch_code'];
                                data['patch_status'] = 'TIP_INDEX_FIXED';
                                data['fd_ids'] = '';
                                var prompt = $rootScope.language.TIP_PATCH_FIXED;
                                //最后一个安装成功
                                $rootScope.progressTips = patchname + $rootScope.language.TIP_INSTALL_FINISH;
                                writeback_patchlog(data, prompt, -1);
                            } else {
                                //否则递归安装下一个子数据包
                                muli_tran_install(i, patch);
                            }
                        }
                    });
                };

                //判断安装数据包前是否需要前置表操作
                var before_install_logic = function(patch) {
                    if(patch.basename[2] == '3') {
                        //安装全量基础包之前，删除sku表
                        if(patch.patch_type == '全量') {
                            var promise = [];
                            //sku包
                            promise.push(dbDelete('PosSku', {}));
                            return $q.all(promise);
                        }
                    }
                    //console.log(patch);
                    //console.log(patch.basename[2]);
                    if(patch.basename[2] == '0'){
                        //if(patch.patch_type == '全量') {
                            var promise = [];
                            //sku包
                            promise.push(dbDelete('PosPurview', {}));
                            return $q.all(promise);
                        //}
                    }
                    var defer = $q.defer();
                    defer.resolve("ok");
                    return defer.promise;
                };

                //补丁包安装
                var patch_install = function (patch) {
                    //install_deferred = $q.defer();
                    //install_promise = install_deferred.promise;
                    before_install_logic(patch).then(function(){
                        if (sys_type == 'pc') {
                            patch_install_pc(patch);
                            return;//install_promise;
                        }
                        patch_install_pad(patch);
                        return;// install_promise;
                    });
                };


                //pc 补丁包安装
                var patch_install_pc = function (patch) {
                    //解压文件并安装
                    unzip_file_zip(patch);

                };
                //pad 补丁包安装
                var patch_install_pad = function (patch) {
                    muli_tran_install('', patch);
                };
                //日志记录
                var writeback_patchlog = function (data, prompt, index) {
                    var patchdata = {};
                    patchdata['patch_code'] = data['patch_code'];
                    patchdata['fd_ids'] = data['fd_ids'];
                    patchdata['patch_status'] = data['patch_status'];
                    patchdata['shop_code'] = $rootScope.current_shop.ShopCode;
                    patchdata['device'] = baison_app.api.deviceId;
                    patchdata['lastchanged'] = timeStamp2String(0, 'datetime');
                    patchdata['remark_log'] = patchdata['shop_code'] + ',' + patchdata['lastchanged'] + ',' + patchdata['patch_code'] + ',' + prompt;
                    apiService('patch/patch/add_patch_log', patchdata).then(function () {
                        $rootScope.patch_status = prompt;
                        if (index !== '') {
                            //传此index参数代表安装结束, 广播
							//baison_app.api.alert({msg:data['patch_code'],title:'patchlog'});
                            $rootScope.$emit('install_finish', data['patch_code']);
                        } else {
                            load_deferred.resolve('success');
                        }
                    });

                };

                //安装逻辑
                var install_logic = function (uncompressPath, patchtype, patchname, patchcode, index, patch) {
                    var ptype = patch.patch_type;
                    baison_app.fs.exist({
                        path: uncompressPath
                    }, function (ret_exist, err) {
                        if (ret_exist.exist && !ret_exist.directory) {
                            $.get(uncompressPath, function (data) {
                                PatchInstall(data, patchtype,ptype).then(function (msg) {
                                    install_deferred_single.resolve({data: 'success'});
                                }).catch(function (err) {
                                    install_deferred_single.resolve({data: 'error'});
                                });
                            });

                        } else {
                            install_deferred_single.resolve({data: 'error'});
                        }
                    });
                };
                //pc安装逻辑
                var pc_install_logic = function (patchtype, patch, patchname, index) {
                    var path = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.patch_code + '\\' + patchname;
                    var patchcode = patch.patch_code;

                    install_logic(path, patchtype, patchname, patchcode, index, patch);
                };
                //安装逻辑
                var pad_install_logic = function (patchtype, patch, patchname, index) {

                    var patchcode = patch.patch_code;
                    var uncompressPath = 'file://' + baison_app.api.fsDir + '/' + patch.basename;//ret.data[0].savePath;
                    uncompressPath = uncompressPath.substr(0, (uncompressPath.length - 4)) + '/' + patchname;
                    install_logic(uncompressPath, patchtype, patchname, patchcode, index, patch);

                };
                var install_deal = function (patchtype, patch, patchname, index) {
                    //console.log(patchname);
                    $rootScope.progressTips = patch.patch_code + '[' + patchtype + ']' + $rootScope.language.TIP_DATAPACK_INSTALL + patchname;
                    install_deferred_single = $q.defer(1);
                    install_promise_single = install_deferred_single.promise;
                    if (sys_type == 'pc') {
                        pc_install_logic(patchtype, patch, patchname, index);
                    } else {
                        pad_install_logic(patchtype, patch, patchname, index);
                    }
                    return install_promise_single;
                };

                return {
                    "writeback_patchlog": writeback_patchlog,
                    "patch_download": patch_download,
                    "patch_install": patch_install,
                    "file_install":file_install
                };
            }
        ])

        //补丁包安装
        .factory('PatchInstall', ['$q','$rootScope', 'dbReplace', 'dbTrans','dbReplaceInto','dbDelete','timeStamp2String', function ($q,$rootScope,dbReplace, dbTrans,dbReplaceInto,dbDelete,timeStamp2String) {
                var promiseInstall = {};

                var install_shop = function (shop) {
                    var _data = [];
                    if (shop == undefined) {
                        return _data;
                    }
                    $.each(shop, function (i, n) {
                        var _s = {};
                        _s.ShopCode = n.distributor_code;
                        _s.ShopName = n.distributor_name;
                        _s.AreaCode = n.area_code;
                        _s.BrandCode = n.brand_code;
                        _s.Id = n.distributor_id;   //商店的ID
                        _s.ShopRebate = n.rebate; //商店折扣
                        _s.ShopPriceIndex = n.terminal_price;//商店定价单索引
                        _data[i] = _s;
                    });
                    return _data;

                };

                //会员卡卡类别
                var install_vip_category = function (vip_category) {
                    var _data = [];
                    if (vip_category == undefined) {
                        return _data;
                    }
                    $.each(vip_category, function (i, n) {
                        var _s = {};
                        _s.id = n.id;
                        _s.cate_code = n.cate_code;
                        _s.cate_name = n.cate_name;
                        _s.rebate = n.rebate;
                        _s.is_stop = n.is_stop;
                        _s.enable_vip_price = n.enable_vip_price;
                        _data[i] = _s;
                    });
                    return _data;
                };

                //多币种获取
                var install_currency_foreign = function (rate) {
                    var _data = [];
                    if (rate == undefined) {
                        return _data;
                    }
                    $.each(rate, function (i, n) {
                        var _s = {};
                        _s.cur_id = n.cur_id;
                        _s.cur_code = n.cur_code;
                        _s.cur_name = n.cur_name;
                        _s.standard = n.standard;
                        _s.rate = n.rate;
                        _s.lastchanged = n.lastchanged;
                        _data[i] = _s;
                    });
                    return _data;
                };

                //用户类别
                var install_user_type = function (role) {
                    var _data = [];
                    if (role == undefined) {
                        return _data;
                    }
                    $.each(role, function (i, n) {
                        var _s = {};
                        _s.role_id = n.role_id;
                        _s.role_code = n.role_code;
                        _s.role_name = n.role_name;
                        _s.role_status = n.role_status;
                        _data[i] = _s;
                    });
                    return _data;
                };

                var install_trade_type = function (cashier_type) {
                    var _data = [];
                    if (cashier_type == undefined) {
                        return _data;
                    }
                    $.each(cashier_type, function (i, n) {
                        var _s = {};
                        _s.CheckOrder = i * 1 + 1;
                        _s.CheckCode = n.trade_type_code;
                        _s.CheckName = n.trade_type_name;
                        _s.CheckConf = '';
                        _data[i] = _s;
                    });
                    return _data;

                };

                var install_record_type = function (record_type) {
                    var _data = [];
                    if (record_type == undefined) {
                        return _data;
                    }
                    $.each(record_type, function (i, n) {
                        var _s = {};
                        _s.record_type_code = n.record_type_code;
                        _s.record_type_name = n.record_type_name;
                        _s.record_type_property = n.record_type_property;
                        _data[i] = _s;
                    });
                    return _data;


                };
                //用户信息
                var install_user = function (user) {
                    var _data = [];
                    if (user == undefined) {
                        return _data;
                    }
                    $.each(user, function (i, n) {
                        var _s = {};
                        _s.UserCode = n.user_code;
                        _s.role_id = n.role_id;
                        _s.UserName = n.user_name;
                        _s.UserPass = n.password;
                        _s.UserSex = n.sex;
                        _s.ShopCode = n.shop_code;
                        _s.UserTel = (n.tel == undefined) ? '' : n.tel;
                        _s.UserStatus = n.status;
                        _s.UserManage = 1;
                        _s.ShopCodeEx = (n.company_shop_code == undefined) ? '' : n.company_shop_code;

                        _s.roleCode = (n.role_code == undefined) ? '' : n.role_code;
                        _s.maxRebate = (n.max_rebate == undefined) ? '' : n.max_rebate;
                        _s.minRebate = (n.min_rebate == undefined) ? '' : n.min_rebate;
                        _s.signatureCode = (n.signature_code == undefined) ? '' : n.signature_code;
                        _s.maxDiscount = (n.max_discount == undefined) ? '' : n.max_discount;
                        _s.maxPrice = (n.max_price_off == undefined) ? '' : n.max_price_off;
                        _s.minPrice = (n.min_price_off == undefined) ? '' : n.min_price_off;
                        _data[i] = _s;
                    });
                    return _data;

                };

                var install_category = function (category) {
                    var _data = [];
                    if (category == undefined) {
                        return _data;
                    }
                    $.each(category, function (i, n) {
                        var _s = {};
                        _s.category_code = n.category_code;
                        _s.category_name = n.category_name;
                        _s.is_fetch = n.is_fetch;
                        _s.p_code = n.p_code;
                        _s.trd_type = n.trd_type;
                        _s.is_show = n.is_show;
                        //多语言适配
                        _s.category_name_zh_tw = n.category_name_zh_tw;
                        _s.category_name_en = n.category_name_en;

                        _data[i] = _s;
                    });
                    return _data;
                };
                //商店和品牌的关联关系表
                var install_shop_and_sort = function (shop_sort) {
                    var _data = [];
                    if (shop_sort == undefined) {
                        return _data;
                    }
                    $.each(shop_sort, function (i, n) {
                        var _s = {};
                        _s.id = n.id;
                        _s.ShopCode = n.shop_code;
                        _s.sort_code = n.sort_code;
                        _data[i] = _s;
                    });
                    return _data;
                };
                //获取当前店铺对应的品牌
                var get_curshop_brandcode = function(){
                    var brand_code_arr = [];
                    var s = $rootScope.current_shop.BrandCode;
                    brand_code_arr = s.split(",");
                    return brand_code_arr;
                };

                var install_goods = function (goods) {
                    var _data = [];
                    if (goods == undefined) {
                        return _data;
                    }
                    var index = 0;
                    $.each(goods, function (i, n) {
                        var brand_code_arr = get_curshop_brandcode();
                        if(brand_code_arr.length > 0){
                            $.each(brand_code_arr,function(j,m){
                            	
                                if(m == n.brand_code){
                                   var _s = {};
                                    _s.GoodsCode = n.goods_code;
                                    _s.GoodsName = n.goods_name;
                                    _s.GoodsChenlie = '';
                                    _s.GoodsStatus = n.status;
                                    _s.CategoryCode = n.category_code;
                                    _s.season_name = n.season_name;
                                    _s.goods_img = n.goods_img;
                                    _s.SortCode = n.sort_code;
                                    _s.is_hot = n.is_hot;
                                    _s.price = n.price;
                                    _s.brand_code = n.brand_code;
                                    _s.weight= n.weight;
                                    _s.unit_name= n.unit_name;
                                    //多语言适配
                                    _s.GoodsName_zh_tw = n.goods_name_zh_tw == undefined ?'':n.goods_name_zh_tw;
                                    _s.GoodsName_en = n.goods_name_en == undefined ?'':n.goods_name_en;
                                    _data.push(_s);
                                }else if(n.brand_code == ''){
                                    var _s = {};
                                    _s.GoodsCode = n.goods_code;
                                    _s.GoodsName = n.goods_name;
                                    _s.GoodsChenlie = '';
                                    _s.GoodsStatus = n.status;
                                    _s.CategoryCode = n.category_code;
                                    _s.season_name = n.season_name;
                                    _s.goods_img = n.goods_img;
                                    _s.SortCode = n.sort_code;
                                    _s.is_hot = n.is_hot;
                                    _s.price = n.price;
                                    _s.brand_code = n.brand_code;
                                    _s.weight= n.weight;
                                    _s.unit_name= n.unit_name;
                                    //多语言适配
                                    _s.GoodsName_zh_tw = n.goods_name_zh_tw == undefined ?'':n.goods_name_zh_tw;
                                    _s.GoodsName_en = n.goods_name_en == undefined ?'':n.goods_name_en;
                                    _data.push(_s);
                                }
                            });
                        }else{
                            var _s = {};
                            _s.GoodsCode = n.goods_code;
                            _s.GoodsName = n.goods_name;
                            _s.GoodsChenlie = '';
                            _s.GoodsStatus = n.status;
                            _s.CategoryCode = n.category_code;
                            _s.season_name = n.season_name;
                            _s.goods_img = n.goods_img;
                            _s.SortCode = n.sort_code;
                            _s.is_hot = n.is_hot;
                            _s.price = n.price;
                            _s.brand_code = n.brand_code;
                            _s.weight= n.weight;
                            _s.unit_name= n.unit_name;
                            //多语言适配
                            _s.GoodsName_zh_tw = n.goods_name_zh_tw == undefined ?'':n.goods_name_zh_tw;
                            _s.GoodsName_en = n.goods_name_en == undefined ?'':n.goods_name_en;
                            _data.push(_s);
                        }
                        

                        
                    });
                    return _data;


                };

                var install_sku = function (sku,ptype) {
                    //baison_app.api.alert({msg:sku,title:'sku'});

                    var _data = [];
                    if (sku == undefined) {
                        return _data;
                    }
                    $.each(sku, function (i, n) {
                        var brand_code_arr = get_curshop_brandcode();
                        if(brand_code_arr.length > 0){
                            $.each(brand_code_arr,function(j,m){
                                if(m == n.brand_code){
                                    var _s = {};
                                    _s.SkuCode = n.sku;
                                    _s.GoodsName = n.goods_name;
                                    _s.GoodsCode = n.goods_code; //todo
                                    _s.SkuPrice = n.price;
                                    _s.SkuVipPrice = n.vip_price;
                                    _s.SkuPropertyName = n.property_name;
                                    _s.ColorCode = n.color_code;
                                    _s.ColorName = n.color_name;
                                    _s.SizeCode = n.size_code;
                                    _s.SizeName = n.size_name;
                                    _s.SkuNum = '0';
                                    _s.SkuChenlie = '0';
                                    //多语言适配
                                    _s.GoodsName_zh_tw = n.goods_name_zh_tw;
                                    _s.GoodsName_en = n.goods_name_en;
                                    _s.SkuPropertyName_zh_tw = n.property_name_zh_tw;
                                    _s.SkuPropertyName_en = n.property_name_en;
                                    _s.ColorName_zh_tw = n.color_name_zh_tw;
                                    _s.ColorName_en = n.color_name_en;
                                    _s.SizeName_zh_tw = n.size_name_zh_tw;
                                    _s.SizeName_en = n.size_name_en;
                                    _s.BrandCode = n.brand_code;
									
                                    _data.push(_s);  
                                }else if(n.brand_code == ''){
                                    console.log(n.brand_code);
                                    var _s = {};
                                    _s.SkuCode = n.sku;
                                    _s.GoodsName = n.goods_name;
                                    _s.GoodsCode = n.goods_code; //todo
                                    _s.SkuPrice = n.price;
                                    _s.SkuVipPrice = n.vip_price;
                                    _s.SkuPropertyName = n.property_name;
                                    _s.ColorCode = n.color_code;
                                    _s.ColorName = n.color_name;
                                    _s.SizeCode = n.size_code;
                                    _s.SizeName = n.size_name;
                                    _s.SkuNum = '0';
                                    _s.SkuChenlie = '0';
                                    //多语言适配
                                    _s.GoodsName_zh_tw = n.goods_name_zh_tw;
                                    _s.GoodsName_en = n.goods_name_en;
                                    _s.SkuPropertyName_zh_tw = n.property_name_zh_tw;
                                    _s.SkuPropertyName_en = n.property_name_en;
                                    _s.ColorName_zh_tw = n.color_name_zh_tw;
                                    _s.ColorName_en = n.color_name_en;
                                    _s.SizeName_zh_tw = n.size_name_zh_tw;
                                    _s.SizeName_en = n.size_name_en;
                                    _s.BrandCode = n.brand_code;
									
                                   _data.push(_s);  
                                }
                            });
                        }else{
                            var _s = {};
                            _s.SkuCode = n.sku;
                            _s.GoodsName = n.goods_name;
                            _s.GoodsCode = n.goods_code; //todo
                            _s.SkuPrice = n.price;
                            _s.SkuVipPrice = n.vip_price;
                            _s.SkuPropertyName = n.property_name;
                            _s.ColorCode = n.color_code;
                            _s.ColorName = n.color_name;
                            _s.SizeCode = n.size_code;
                            _s.SizeName = n.size_name;
                            _s.SkuNum = '0';
                            _s.SkuChenlie = '0';
                            //多语言适配
                            _s.GoodsName_zh_tw = n.goods_name_zh_tw;
                            _s.GoodsName_en = n.goods_name_en;
                            _s.SkuPropertyName_zh_tw = n.property_name_zh_tw;
                            _s.SkuPropertyName_en = n.property_name_en;
                            _s.ColorName_zh_tw = n.color_name_zh_tw;
                            _s.ColorName_en = n.color_name_en;
                            _s.SizeName_zh_tw = n.size_name_zh_tw;
                            _s.SizeName_en = n.size_name_en;
                            _s.BrandCode = n.brand_code;
							
                            _data.push(_s);    
                        }
                        
                    });
                    
                    promiseInstall['PosSku'] = dbTrans.begin().then(function (success) {
                        var promisePromotions = [];
                        // if(ptype == '全量' || ptype == 1){
                        // 	//baison_app.api.alert({msg:_data.length,title:'sku'});
                        // 	//清空PosSku数据表
                        // 	promisePromotions['PosSku_del'] = dbDelete('PosSku', {}).then(function(){
                        // 		promisePromotions['PosSku_add'] = dbReplaceInto('PosSku', _data, [
		                //             'SkuCode', 'GoodsName', 'GoodsCode', 'SkuPrice', 'SkuVipPrice', 'SkuPropertyName',
		                //              'ColorCode', 'ColorName', 'SizeCode', 'SizeName', 'SkuNum', 'SkuChenlie', 
		                //              'GoodsName_zh_tw', 'GoodsName_en',  'SkuPropertyName_zh_tw', 
		                //              'SkuPropertyName_en', 'ColorName_zh_tw', 'ColorName_en', 'SizeName_zh_tw',
		                //               'SizeName_en','BrandCode']);
                        // 	});
                        	
                        // }else
                        {
                        	promisePromotions['PosSku_add'] = dbReplaceInto('PosSku', _data, [
                            'SkuCode', 'GoodsName', 'GoodsCode', 'SkuPrice', 'SkuVipPrice', 'SkuPropertyName',
                             'ColorCode', 'ColorName', 'SizeCode', 'SizeName', 'SkuNum', 'SkuChenlie', 
                             'GoodsName_zh_tw', 'GoodsName_en',  'SkuPropertyName_zh_tw', 
                             'SkuPropertyName_en', 'ColorName_zh_tw', 'ColorName_en', 'SizeName_zh_tw',
                              'SizeName_en','BrandCode']);
                        }
                        
                        return $q.all(promisePromotions);
                    }).then(function (success) {
                        dbTrans.commit();
                    }).catch(function (err) {

                        //baison_app.api.alert({msg: err})

                        dbTrans.rollback();
                    });

                };

                var install_color = function (data) {
                };
                var install_size = function (data) {
                };

                //促销规则更新
                var install_promotion = function (promotion, trd_type) {
                    if (typeof promotion == 'undefined' || promotion.length <= 0) {
                        return;
                    }
                    //crm促销
                    if (trd_type == 'crm') {
                        promiseInstall['promotion'] = dbTrans.begin().then(function (success) {
                            var promisePromotions = [];
                            var _time = timeStamp2String(0, 'datetime');
                            $.each(promotion, function (i, n) {
                                if(parseInt(n.is_check) == 1 && n.end_time >= _time ){

                                
                                var subPromise;
                                //判断是否店铺级
                                var _is_shop = 0;
                                var _promotion_shop_type = 0;
                                if (Object.keys(n.shop_list).length > 0) {
                                    _is_shop = 1;
                                    _promotion_shop_type = 1
                                }
                                //判断是否商品级
                                var _is_goods = 0;
                                var _promotion_goods_type = 0;
                                if (Object.keys(n.goods_list).length > 0) {
                                    _is_goods = 1;
                                    _promotion_goods_type = 1;
                                }

                                var insert_data = [{
                                        promotion_rule_id: n.promo_id,
                                        record_code: n.promo_code,
                                        promotion_type: parseInt(n.type),
                                        name: n.promo_name,
                                        short_name: n.promo_name,
                                        begin_time: n.start_time,
                                        end_time: n.end_time,
                                        is_share: parseInt(n.rule_type),
                                        is_coupon: parseInt(n.is_bind),
                                        is_audit: parseInt(n.is_check),
                                        is_stop: parseInt(n.is_stop),
                                        remark: n.remark,
                                        relation_code: '',
                                        init_code: '',
                                        record_time: n.is_add_time,
                                        is_added_profits: 0,
                                        is_promotion_day_restrict: 0,
                                        promotion_day: '',
                                        apply_target: '',
                                        promotion_shop_type: _promotion_shop_type,
                                        is_region: 0,
                                        promotion_goods_type: _promotion_goods_type,
                                        is_category: 0,
                                        is_goods: _is_goods,
                                        is_return: 0,
                                        is_exchange: 0,
                                        is_shop: _is_shop,
                                        is_double_pro:1,
                                        is_use_more:n.is_use_more
                                    }];

                                subPromise = dbReplaceInto('PosPromotionRule', insert_data, ['promotion_rule_id', 'record_code', 'promotion_type', 'name', 'short_name', 'begin_time',
                            'end_time', 'is_share', 'is_coupon', 'is_audit',
                            'is_stop', 'remark', 'relation_code', 'init_code',
                            'record_time', 'is_added_profits', 'is_promotion_day_restrict', 'promotion_day', 'apply_target', 'promotion_shop_type', 'is_region', 'promotion_goods_type',
                            'is_category', 'is_goods', 'is_return', 'is_exchange', 'is_shop', 'is_double_pro', 'is_use_more'])
                                        .then(function () {
                                            var insert_option = [{
                                                    option_id: n.promo_id,
                                                    pid: n.promo_id,
                                                    promotion_type: n.type,
                                                    vip_price: n.money,
                                                    customer_price: n.money,
                                                    customer_num: n.num,
                                                    reduce_price: n.present_money,
                                                    gift_total_price: 0,
                                                    gift_total_num: n.present_num,
                                                    rebate: n.rebate,
                                                    remark: '',
                                                    priority: 0
                                                }];

                                            return dbReplaceInto('PosPromotionRuleOption', insert_option, ['option_id', 'pid', 'promotion_type', 'vip_price', 'customer_price', 'customer_num', 'reduce_price', 'gift_total_price', 'gift_total_num', 'rebate', 'remark', 'priority']);
                                
                                        })
                                        .then(function (success) {
                                            if (Object.keys(n.goods_list).length > 0) {
                                                var insert_goods = [];
                                                $.each(n.goods_list, function (goods_k, goods) {
                                                    insert_goods[goods_k] = {
                                                        rule_goods_id: goods.promo_goods_id,
                                                        pid: goods.pid,
                                                        remark: goods.remark,
                                                        goods_id: goods.goods_id,
                                                        goods_code: goods.goods_code,
                                                        goods_name: goods.goods_name,
                                                        sku: goods.sku,
                                                        record_code: n.promo_code
                                                    };
                                                });
                                                return dbReplaceInto('PosPromotionRuleGoods', insert_goods, ['rule_goods_id', 'pid', 'remark', 'goods_id', 'goods_code', 'goods_name', 'sku', 'record_code']);
                                    
                                            }
                                        })
                                        .then(function (success) {
                                            if (Object.keys(n.group).length > 0) {

                                                var group_promise = [];

                                                $.each(n.group, function (group_k, group_v) {

                                                    var insert_group = [{
                                                            promotion_rule_id: n.promo_id,
                                                            promo_group_id: group_v.promo_group_id,
                                                            pid: group_v.pid,
                                                            promo_group_name: group_v.promo_group_name,
                                                            remark: group_v.remark,
                                                            record_code: n.promo_code
                                                        }];
                                                    //套组
                                                    group_promise[group_k] = dbReplaceInto('PosPromotionRuleGroup', insert_group, ['promotion_rule_id', 'promo_group_id', 'pid', 'promo_group_name', 'remark', 'record_code'])
                                                    
                                                            .then(function (success) {

                                                                if (Object.keys(group_v).length > 0) {

                                                                    var group_mid_promise = [];

                                                                    $.each(group_v.group_mid, function (group_mid_k, group_mid_v) {

                                                                        var insert_group_mid = [{
                                                                                promo_group_mid_id: group_mid_v.promo_group_mid_id,
                                                                                promotion_rule_id: group_mid_v.promo_group_id,
                                                                                pid: group_mid_v.pid,
                                                                                name: group_mid_v.name,
                                                                                remark: group_mid_v.remark,
                                                                                record_code: n.promo_code
                                                                            }];
                                                                        //组别
                                                                        group_mid_promise[group_mid_k] = dbReplaceInto('PosPromotionRuleGroupMid', insert_group_mid, ['promo_group_mid_id', 'promotion_rule_id', 'pid', 'name', 'remark', 'record_code'])
                                                                        
                                                                                .then(function (success) {
                                                                                    if (Object.keys(group_mid_v.group_detail).length > 0) {
                                                                                        var group_detail_promise = [];
                                                                                        $.each(group_mid_v.group_detail, function (_g_detail_k, _g_detail_v) {
                                                                                            //商品
                                                                                            var insert_group_detail = [{
                                                                                                    promo_group_detail_id: _g_detail_v.promo_group_detail_id,
                                                                                                    promotion_rule_id: _g_detail_v.pid,
                                                                                                    promo_group_mid_id: parseInt(_g_detail_v.promo_group_mid_id),
                                                                                                    promo_group_id: group_v.promo_group_id,
                                                                                                    goods_code: _g_detail_v.goods_code,
                                                                                                    goods_name: _g_detail_v.goods_name,
                                                                                                    sku: _g_detail_v.sku,
                                                                                                    num: _g_detail_v.num,
                                                                                                    price: _g_detail_v.price,
                                                                                                    record_code: n.promo_code
                                                                                                }];
                                                                                            group_detail_promise[_g_detail_k] = dbReplaceInto('PosPromotionRuleGroupDetail', insert_group_detail, ['promo_group_detail_id', 'promotion_rule_id', 'promo_group_mid_id', 'promo_group_id', 'goods_code', 'goods_name', 'sku', 'num', 'price', 'record_code']);
                                                                                
                                                                                        });
                                                                                        return $q.all(group_detail_promise);
                                                                                    }
                                                                                });
                                                                    });

                                                                    return $q.all(group_mid_promise);
                                                                }
                                                            });
                                                });

                                                return $q.all(group_promise);
                                            }
                                        })
                                        .then(function (success) {
                                            if (Object.keys(n.gift_list).length > 0) {

                                                var insert_gift = [];
                                                $.each(n.gift_list, function (gift_k, gift) {
                                                    insert_gift[gift_k] = {
                                                        rule_gift_id: gift.promo_gift_id,
                                                        pid: gift.pid,
                                                        remark: gift.remark,
                                                        goods_id: gift.goods_id,
                                                        goods_code: gift.goods_code,
                                                        sku: gift.sku,
                                                        goods_name: gift.goods_name,
                                                        record_code: n.promo_code,
                                                        price: gift.price
                                                    };
                                                });
                                                return dbReplaceInto('PosPromotionRuleGift', insert_gift, ['rule_gift_id', 'pid', 'remark', 'goods_id', 'goods_code', 'sku', 'goods_name','record_code', 'price']);
                                                }
                                        })
                                        .then(function (success) {
                                            if (Object.keys(n.shop_list).length > 0) {
                                                var insert_shop = [];
                                                $.each(n.shop_list, function (shop_k, shop) {
                                                    insert_shop[shop_k] = {
                                                        rule_shop_id: shop.promo_shop_id,
                                                        shop_id: shop.promo_shop_id,
                                                        pid: shop.pid,
                                                        remark: shop.remark,
                                                        record_code: n.promo_code,
                                                        shop_code: shop.shop_code,
                                                        shop_name: shop.shop_name
                                                    };
                                                });
                                                return dbReplaceInto('PosPromotionRuleShop', insert_shop, ['rule_shop_id', 'shop_id', 'pid', 'remark', 'record_code', 'shop_code', 'shop_name']);
                                    
                                            }
                                        });
                                
                                promisePromotions.push(subPromise);
                                }
                            });
                            
                            return $q.all(promisePromotions);
                            
                        }).then(function (success) {
                            dbTrans.commit();
                        }).catch(function (err) {
                            dbTrans.rollback();
                        })
                    } else {

                        promiseInstall['promotion'] = dbTrans.begin().then(function (success) {
                            var promisePromotions = [];
                            $.each(promotion, function (i, n) {
                                var subPromise;
                               
                                //更新主表
                                var insert_data = [{
                                        promotion_rule_id: n.promotion_rule_id,
                                        record_code: n.record_code,
                                        promotion_type: n.promotion_type,
                                        relation_code: n.relation_code,
                                        init_code: n.init_code,
                                        record_time: n.record_time,
                                        name: n.name,
                                        short_name: n.short_name,
                                        begin_time: n.begin_time,
                                        end_time: n.end_time,
                                        is_added_profits: n.is_added_profits,
                                        is_promotion_day_restrict: n.is_promotion_day_restrict,
                                        promotion_day: n.promotion_day,
                                        apply_target: n.apply_target,
                                        promotion_shop_type: n.promotion_shop_type,
                                        is_region: n.is_region,
                                        promotion_goods_type: n.promotion_goods_type,
                                        is_category: n.is_category,
                                        is_goods: n.is_goods,
                                        is_shop:n.is_shop,
                                        is_share: n.is_share,
                                        is_return: n.is_return,
                                        is_exchange: n.is_exchange,
                                        is_coupon: n.is_coupon,
                                        is_audit: n.is_audit,
                                        is_stop: n.is_stop,
                                        is_double_pro:n.is_double_pro,
                                        is_use_more:n.is_use_more
                                    }];

                                subPromise = dbReplace('PosPromotionRule', insert_data, ['promotion_rule_id'],
                                        ['is_coupon', 'is_exchange', 'is_return', 'is_share', 'is_goods','is_shop',
                                            'is_category', 'promotion_goods_type', 'is_region', 'promotion_shop_type',
                                            'apply_target', 'promotion_day', 'is_promotion_day_restrict', 'is_added_profits',
                                            'end_time', 'begin_time', 'short_name', 'name', 'record_time', 'init_code', 'relation_code', 'promotion_type',
                                            'is_audit', 'is_stop'])
                                        .then(function (success) {
                                            //更新促销选项
                                            if (n.option_list.length > 0) {
                                                var insert_option = [];
                                                $.each(n.option_list, function (option_k, option) {
                                                    insert_option[option_k] = {
                                                        option_id: option.option_id,
                                                        pid: option.pid,
                                                        remark: option.remark,
                                                        promotion_type: option.promotion_type,
                                                        vip_price: option.vip_price,
                                                        customer_price: option.customer_price,
                                                        customer_num: (option.customer_num==undefined)?0:option.customer_num,
                                                        reduce_price: option.reduce_price,
                                                        gift_total_price: option.gift_total_price,
                                                        gift_total_num: option.gift_total_num,
                                                        rebate: option.rebate,
                                                        priority: option.priority
                                                    };
                                                });
                                                return dbReplace('PosPromotionRuleOption', insert_option, ['pid','promotion_type'],
                                                        ['promotion_type', 'vip_price', 'customer_price', 'remark',
                                                            'reduce_price', 'gift_total_price', 'gift_total_num', 'rebate', 'priority']);
                                            }
                                        })
                                        .then(function (success) {
                                            //商品类别
                                            if (n.promotion_goods_type == 1 && n.is_category == 1 && n.category_list.length > 0) {
                                                var insert_category = [];
                                                $.each(n.category_list, function (category_k, category) {
                                                    insert_category[category_k] = {
                                                        rule_category_id: category.rule_category_id,
                                                        pid: category.pid,
                                                        category_id: category.category_id,
                                                        category_code: category.category_code,
                                                        category_name: category.category_name,
                                                        remark: category.remark,
                                                        record_code: category.record_code
                                                    };
                                                });
                                                return dbReplace('PosPromotionRuleCategory', insert_category, ['category_id', 'pid'],
                                                        ['category_id', 'category_code', 'category_name', 'remark']);
                                            }
                                        })
                                        .then(function (success) {
                                            //商品
                                            if (n.promotion_goods_type == 1 && n.is_goods != 0 && n.goods_list.length > 0) {
                                                var insert_goods = [];
                                                $.each(n.goods_list, function (goods_k, goods) {
                                                    insert_goods[goods_k] = {
                                                        rule_goods_id: goods.rule_goods_id,
                                                        pid: goods.pid,
                                                        remark: goods.remark,
                                                        record_code: goods.record_code,
                                                        goods_id: goods.goods_id,
                                                        goods_code: goods.goods_code,
                                                        sku:goods.sku,
                                                        goods_name: goods.goods_name
                                                    };
                                                });
                                                return dbReplace('PosPromotionRuleGoods', insert_goods, ['sku', 'pid'],
                                                        ['goods_id', 'goods_code','sku', 'goods_name', 'remark']);
                                            }

                                        })
                                        .then(function (success) {
                                            //赠品
                                            if (n.gift_list.length > 0) {
                                                var insert_gift = [];
                                                $.each(n.gift_list, function (gift_k, gift) {
                                                    insert_gift[gift_k] = {
                                                        rule_gift_id: gift.rule_gift_id,
                                                        pid: gift.pid,
                                                        remark: gift.remark,
                                                        record_code: gift.record_code,
                                                        goods_id: gift.goods_id,
                                                        sku:gift.sku,
                                                        goods_code: gift.goods_code,
                                                        goods_name: gift.goods_name,
                                                        
                                                    };
                                                });
                                                //console.log(JSON.stringify(insert_gift));
                                                return dbReplace('PosPromotionRuleGift', insert_gift, ['sku', 'pid'],
                                                        ['goods_id', 'goods_code','sku', 'goods_name', 'remark']);
                                            }
                                        })
                                        .then(function (success) {
                                            //店铺区域
                                            if (n.promotion_shop_type == 1 && n.is_region == 1 && n.region_list.length > 0) {
                                                var insert_region = [];
                                                $.each(n.region_list, function (region_k, region) {
                                                    insert_region[region_k] = {
                                                        rule_region_id: region.rule_region_id,
                                                        pid: region.pid,
                                                        remark: region.remark,
                                                        record_code: region.record_code,
                                                        region_id: region.region_id,
                                                        region_code: region.region_code,
                                                        region_name: region.region_name
                                                    };
                                                });
                                                return dbReplace('PosPromotionRuleRegion', insert_region, ['region_id','pid'],
                                                        ['region_id', 'region_code', 'region_name', 'remark']);
                                            }

                                        })
                                        .then(function (success) {
                                            //店铺
                                            if (n.promotion_shop_type == 1 && n.is_shop != 0 && n.shop_list.length > 0) {
                                                var insert_shop = [];
                                                $.each(n.shop_list, function (shop_k, shop) {
                                                    insert_shop[shop_k] = {
                                                        rule_shop_id: shop.rule_shop_id,
                                                        pid: shop.pid,
                                                        remark: shop.remark,
                                                        record_code: shop.record_code,
                                                        shop_id: shop.shop_id,
                                                        shop_code: shop.shop_code,
                                                        shop_name: shop.shop_name
                                                    };
                                                });
                                                return dbReplace('PosPromotionRuleShop', insert_shop, ['shop_id','pid'],
                                                        ['shop_id', 'shop_code', 'shop_name', 'remark']);
                                            }
                                        })
                                        ;
                                promisePromotions.push(subPromise);
                            });
                            return $q.all(promisePromotions);
                        }).then(function (success) {
                            dbTrans.commit();
                        }).catch(function (err) {
                            //console.log(JSON.stringify(err));
                            dbTrans.rollback();
                        });
                    }
                };

                //小票模版
                var install_xiaopiao = function (xiaopiao) {
                    var _data = [];
                    if (xiaopiao == undefined) {
                        return _data;
                    }
                    $.each(xiaopiao, function (i, n) {
                        var _s = {};

                        _s.name = n.name;  //小票模板名
                        _s.width = n.width; //小票宽度
                        _s.content = n.content;//内容
                        _s.id = n.id; //主键
                        _s.sys = n.sys; //是否系统内置，0否，1是
                        _s.lastchanged = n.lastchanged; //时间戳标识

                        _data[i] = _s;
                    });
                    return _data;
                };

                //库存模版
                var install_stock = function (stock) {

                    var _data = [];
                    if (stock == undefined) {
                        return _data;
                    }
                    $.each(stock, function (i, n) {
                        var _s = {};

                        _s.name = n.name;  //小票模板名
                        _s.width = n.width; //小票宽度
                        _s.content = n.content;//内容
                        _s.id = n.id; //主键
                        _s.sys = n.sys; //是否系统内置，0否，1是
                        _s.lastchanged = n.lastchanged; //时间戳标识

                        _data[i] = _s;
                    });
                    return _data;
                };

                //仓库
                var install_store = function (store) {
                    var _data = [];
                    if (store == undefined) {
                        return _data;
                    }
                    $.each(store, function (i, n) {
                        var _s = {};
                        _s.store_code = n.store_code;
                        _s.store_name = n.store_name;
                        _s.store_id = n.store_id;
                        _s.store_property = n.store_property;
                        //_s.lastchanged = n.lastchanged;
                        _s.status = n.status;
                        _s.pid = n.pid;    //仓库的组织id
                        _data[i] = _s;
                    });
                    return _data;
                };

                //品类
                var install_sort = function (sort) {

                    var _data = [];
                    if (sort == undefined) {
                        return _data;
                    }
                    $.each(sort, function (i, n) {
                        var _s = {};
                        _s.sort_code = n.sort_code;
                        _s.sort_name = n.sort_name;
                        _s.is_fetch = n.is_fetch;
                        _s.p_code = n.p_code;
                        _s.is_show = n.is_show;
                        _data[i] = _s;
                    });
                    return _data;
                };



                //关联商品表
                var install_AssociatedGoods = function (AssociatedGoods) {
                    var _data = [];
                    if (AssociatedGoods == undefined) {
                        return _data;
                    }
                    $.each(AssociatedGoods, function (i, n) {
                        var _s = {};
                        _s.GoodsCode = n.GoodsCode;
                        _s.Id = n.Id;
                        _s.CollectionCode = n.CollectionCode;
                        _data[i] = _s;
                    });
                    return _data;
                };

                //皮肤类型
                var install_skin = function (skin) {

                    var _data = [];
                    if (skin == undefined) {
                        return _data;
                    }
                    $.each(skin, function (i, n) {
                        var _s = {};
                        _s.skin_code = n.property_code;
                        _s.skin_name = n.property_name;
                        _data[i] = _s;
                    });
                    return _data;
                };

                //APP权限
                var install_purview = function (purview) {

                    var _data = [];
                    if (purview == undefined) {
                        return _data;
                    }

                    $.each(purview, function (i, n) {
                        var _s = {};
                        _s.role_purview_id = n.role_purview_id;
                        _s.purview_id = n.purview_id;
                        _s.role_id = n.role_id;
                        _s.name = n.name;
                        _s.url = n.url;
                        _data[i] = _s;
                    });
                    return _data;
                };
                //退货原因
                var install_return_reason = function (reason) {

                    var _data = [];
                    if (reason == undefined) {
                        return _data;
                    }

                    $.each(reason, function (i, n) {
                        var _s = {};
                        _s.trade_type_code = n.trade_type_code;
                        _s.trade_type_name = n.trade_type_name;
                        _s.remark = n.remark;
                        _s.return_reason_id = n.return_reason_id;
                        _s.return_desc = n.return_desc;
                        _s.sys = n.sys;
                        _data[i] = _s;
                    });
                    return _data;

                };
                
                //商品调价表
                var install_adjust_price = function(adjust_price,ptype){
                    var _data = [];
                    if (adjust_price == undefined) {
                        return _data;
                    }
                    
                    var subPromise;
                    var insert_data = [];
                    //console.log(adjust_price);
                    promiseInstall['adjust'] = dbTrans.begin().then(function (success) {
                        var promisePromotions = [];
                        $.each(adjust_price.shop_list, function (i, n) {
                            
                            insert_data.push({
                                    AdjustId:n.pid,
                                    Shop_Code: n.shop_code,
                                    Start_Date: n.start_date,
                                    End_Date: n.end_date,
                                    Adjust_Type: n.type,
                                    Lastchanged:n.lastchanged
                                });
                        });
                        subPromise = dbReplaceInto('PosSku_adjust_price', insert_data, ['AdjustId', 'Shop_Code', 'Start_Date', 'End_Date', 'Adjust_Type', 'Lastchanged']).then(function () {
                  
                                var insert_detail =[];
                                $.each(adjust_price.goods_list, function (i, val) {
                                    
                                    insert_detail.push({
                                        AdjustId:val.pid,
                                        SkuCode: val.sku,
                                        GoodsCode: val.goods_code,
                                        Price: val.price,
                                        Price1:val.price1,
                                        Price2:val.price2,
                                        Price3:val.price3,
                                        Price4:val.price4,
                                        Rebate:val.rebate
                                    });
                                });
                                    return dbReplaceInto('PosSku_adjust_price_detail', insert_detail, ['AdjustId', 'SkuCode', 'GoodsCode', 'Price', 'Price1', 'Price2', 'Price3', 'Price4', 'Rebate']);
                                });  
                        promisePromotions.push(subPromise);
                        
                        return $q.all(promisePromotions);
                    }).then(function (success) {
                        dbTrans.commit();
                    }).catch(function (err) {
                        //console.log(err);
                        dbTrans.rollback();
                    });
                    
                    
                   
                    
                };
                //商品定价单
                var install_goods_pricing = function(goods_price){
                    var _data = [];
                    if (goods_price == undefined) {
                        return _data;
                    }

                    $.each(goods_price, function (i, n) {
                        var _s = {};
                        _s.SkuCode = n.sku;
                        _s.GoodsCode = n.goods_code;
                        _s.ColorCode = n.color_code;
                        _s.SizeCode = n.size_code;
                        _s.Price = n.price;
                        _s.Price1 = n.price1;
                        _s.Price2 = n.price2;
                        _s.Price3 = n.price3;
                        _s.Price4 = n.price4;
                        _data[i] = _s;
                    });
                    promiseInstall['PosSku_pricing'] = dbTrans.begin().then(function (success) {
                        return  dbReplaceInto('PosSku_pricing', _data, ['SkuCode', 'GoodsCode', 'ColorCode', 'SizeCode', 'Price', 'Price1', 'Price2', 'Price3', 'Price4']);
                    }).then(function (success) {
                        dbTrans.commit();
                    }).catch(function (err) {
                        dbTrans.rollback();
                    });
                };

                //商品条码
                var install_goods_barcode = function(goods_barcode){
                    var _data = [];
                    if (goods_barcode == undefined) {
                        return _data;
                    }

                    $.each(goods_barcode, function (i, n) {
                        var _s = {};
                        _s.SkuCode = n.sku;
                        _s.GoodsCode = n.goods_code;
                        _s.BarCode = n.bar_code;
                        _data[i] = _s;
                    });
                    promiseInstall['PosBarcode'] = dbTrans.begin().then(function (success) {
                        return  dbReplaceInto('PosBarcode', _data, ['SkuCode', 'GoodsCode', 'BarCode']);
                    }).then(function (success) {
                        dbTrans.commit();
                    }).catch(function (err) {
                        dbTrans.rollback();
                    });
                };
                
                //商品价格 (ipos调价表) 2016-03-23
                /*
                var install_goods_price = function (goods_price) {
                    var _data = [];
                    if (goods_price == undefined) {
                        return _data;
                    }

                    $.each(goods_price, function (i, n) {
                        var _s = {};
                        _s.shop_code = n.shop_code;
                        _s.goods_code = n.goods_code;
                        _s.color_code = n.color_code;
                        _s.size_code = n.size_code;
                        _s.org_code = n.org_code;
                        _s.price = n.price;
                        _s.price1 = n.price1;
                        _s.price2 = n.price2;
                        _s.rebate = n.rebate;
                        _s.rebate_price = n.rebate_price;
                        _s.purchase_price = n.purchase_price;
                        _s.purchase_price1 = n.purchase_price1;
                        _s.start_date = n.start_date;
                        _s.end_date = n.end_date;

                        _data[i] = _s;
                    });

                    promiseInstall['PosGoodsPrice'] = dbTrans.begin().then(function (success) {
                        return  dbReplace('PosGoodsPrice', _data, ['shop_code', 'goods_code', 'color_code', 'size_code'], ['org_code', 'price', 'price1', 'price2', 'rebate', 'rebate_price', 'purchase_price', 'purchase_price1', 'start_date', 'end_date']);
                    }).then(function (success) {
                        dbTrans.commit();
                    }).catch(function (err) {

                        //baison_app.api.alert({msg: err})

                        dbTrans.rollback();
                    });
                };*/

                return function (_data, patchtype,ptype) {
                    try {
                        var data = JSON.parse(_data);//;$.parseJSON(data);
                    } catch (e) {
//                        console.log(_data);
//                        console.log(e);
                    }

                    if (patchtype == 'sku') {
                        var sku = data;
                        //console.log(sku.length);
                        install_sku(sku,ptype);
                        
                        
                    } else if (patchtype == 'promotion') {
                        var promotion = data.promotion;
                        //console.log(promotion.length);
                        //console.log(data.trd_type);
                        install_promotion(promotion, data.trd_type);

                    } else if (patchtype == 'skufile') {
                        //baison_app.api.alert({msg:'here'});
                        //baison_app.api.alert({msg:data.goods.length,title:'data'});
                        var goods = data.goods;
                        //console.log(goods.length);
                        var goods_data = install_goods(goods);
                        promiseInstall['PosGoods'] = dbTrans.begin().then(function (success) {
                            return dbReplaceInto('PosGoods', goods_data, ['GoodsCode', 'GoodsName', 'GoodsChenlie', 'GoodsStatus', 'CategoryCode', 'season_name', 'goods_img', 'SortCode', 'is_hot', 'price', 'brand_code', 'weight', 'unit_name']);
                        }).then(function (success) {
                            dbTrans.commit();
                        }).catch(function (err) {
                            dbTrans.rollback();
                        });
                    } else if (patchtype == 'adjust_price') {//ipos调价
                        var adjust_price = data;
                        install_adjust_price(adjust_price);
                    }else if (patchtype == 'goods_price') {//ipos定价
                        var goods_price = data;
                        install_goods_pricing(goods_price);

                    }else if (patchtype == 'goods_barcode') {//商品条码
                        var goods_barcode = data;
                        install_goods_barcode(goods_barcode);

                    } else if (patchtype == 'other') {

                        var shop = data.shop;
                        var shop_data = install_shop(shop);

                        var cashier_type = data.cashier_type;
                        var cashier_data = install_trade_type(cashier_type);

						
                        var role_type = data.role;
                        if (data.role != undefined) {
                            role_type = data.role;
                        }
                        var role_data = install_user_type(role_type);

                        var vip_category = [];
                        if (data.vip_category != undefined) {
                            vip_category = data.vip_category;
                        }
                        var vip_category_data = install_vip_category(vip_category);

                        var currency_foreign = [];
                        if (data.rate != undefined) {
                            currency_foreign = data.rate;
                        }
                        var currency_foreign_data = install_currency_foreign(currency_foreign);

                        var record_type = data.record_type;
                        var record_data = install_record_type(record_type);
                        var user = data.user;
                        var user_data = install_user(user);

                        var category = data.category;
                        var category_data = install_category(category);

                        var goods = [];
                        if (data.goods != undefined) {
                            goods = data.goods;
                        }
                        var goods_data = install_goods(goods);
                        //}

                        //关联商品表
                        var AssociatedGoods = data.PosAssociatedGoods;
                        if (data.PosAssociatedGoods == undefined) {
                            AssociatedGoods = [];
                        }
                        var AssociatedGoods_data = install_AssociatedGoods(AssociatedGoods);

						//商店和品牌
						var shop_sort = data.shop_sort;
                        if (data.shop_sort == undefined) {
                            shop_sort = [];
                        }
                        var shop_sort = install_shop_and_sort(shop_sort);

                        var color = data.color;
                        install_color(color);//先不存
                        var size = data.size;
                        install_size(size);//先不存

                        //小票模板
                        var xiaopiao = data.xiaopiao;
                        var xiaopiao_data = install_xiaopiao(xiaopiao);

                        //库存模板
                        var stock = data.stock;
                        if (data.stock == undefined) {
                            stock = [];
                        }
                        var stock_data = install_stock(stock);
                        //仓库
                        var store = data.store;
                        var store_data = install_store(store);

                        //品类
                        var sort = data.sort;
                        var sort_data = install_sort(sort);


                        //皮肤类型
                        var crm_property_set = data.crm_property_set;
                        var skin_data = install_skin(crm_property_set);
                        //店铺权限
                        var purview = data.purview;
                        var purview_data = install_purview(purview);
                        //退货原因
                        var return_reason = data.return_reason;

                        var reason_data = install_return_reason(return_reason);

                        //会员属性
                        var crm_property_code = data.crm_property_code;
                        var crm_property_set = data.crm_property_set;
                        $api.setStorage('crm_property_code', crm_property_code);
                        $api.setStorage('crm_property_set', crm_property_set);
                        promiseInstall['other'] = dbTrans.begin().then(function (success) {
                            var promisePromotions = [];
                            promisePromotions['shop'] = dbReplaceInto('PosShop', shop_data, ['ShopCode', 'ShopName', 'AreaCode', 'BrandCode', 'Id', 'ShopRebate', 'ShopPriceIndex']);
                            //dbReplace('PosShop', shop_data, ['ShopCode'], ['ShopName', 'AreaCode', 'Id','ShopRebate','ShopPriceIndex']);
                            promisePromotions['cashier_type'] = dbReplaceInto('PosCheck', cashier_data, ['CheckOrder', 'CheckCode', 'CheckName', 'CheckConf']);
                    
                            promisePromotions['vip_category'] = dbReplaceInto('Pos_vip_category', vip_category_data, ['id', 'cate_code', 'cate_name', 'rebate', 'is_stop', 'enable_vip_price']);
              
                            promisePromotions['pos_base_record_type'] = dbReplaceInto('pos_base_record_type', record_data, ['record_type_code', 'record_type_name', 'record_type_property']);
                    
                            promisePromotions['PosUser'] = dbReplaceInto('PosUser', user_data, ['UserCode', 'role_id', 'UserName', 'UserPass', 'UserSex', 'ShopCode', 'UserTel', 'UserStatus', 'UserManage', 'ShopCodeEx', 'roleCode', 'maxRebate', 'minRebate', 'signatureCode', 'maxDiscount', 'maxPrice', 'minPrice']);
           
                            
                            //dbReplace('PosUser', user_data, ['UserCode'], ['UserName', 'UserPass', 'UserSex', 'ShopCode', 'UserTel', 'UserManage', 'ShopCodeEx', 'UserStatus', 'roleCode', 'maxRebate', 'minRebate', 'signatureCode', 'maxDiscount', 'maxPrice', 'minPrice']);
                            promisePromotions['role_type'] = dbReplaceInto('Pos_user_type', role_data, ['role_id', 'role_code', 'role_name', 'role_status']);
                    
                            
                            
                            //dbReplace('Pos_user_type', role_data, ['role_id'], ['role_code', 'role_name', 'role_status']);
                            promisePromotions['currency_foreign'] = dbReplaceInto('PosForeignCheck', currency_foreign_data, ['cur_id', 'cur_code', 'cur_name', 'standard', 'rate', 'lastchanged']);
                    
                            
                            
                            //dbReplace('PosForeignCheck', currency_foreign_data, ['cur_id'], ['cur_name', 'cur_code', 'standard', 'rate', 'lastchanged']);

                            promisePromotions['PosCategory'] = dbReplaceInto('PosCategory', category_data, ['category_code', 'category_name', 'is_fetch', 'p_code', 'trd_type', 'is_show','category_name_zh_tw','category_name_en']);

           
                            
                            //dbReplace('PosCategory', category_data, ['category_code', 'trd_type'], ['trd_type', 'category_name', 'is_fetch', 'p_code', 'is_show']);
                            promisePromotions['Pos_shop_and_sort'] = dbReplaceInto('Pos_shop_and_sort', shop_sort, ['id', 'ShopCode', 'sort_code']);
                    
                    
                    
                            
                            
                            //dbReplace('Pos_shop_and_sort', shop_sort, ['id'], ['ShopCode','sort_code']);
                            
                            promisePromotions['PosGoods'] = dbReplaceInto('PosGoods', goods_data, ['GoodsCode', 'GoodsName', 'GoodsChenlie', 'GoodsStatus', 'CategoryCode', 'season_name', 'goods_img', 'SortCode', 'is_hot', 'price', 'brand_code','weight','unit_name','GoodsName_zh_tw','GoodsName_en']);
                    
                            
                            //dbReplace('PosGoods', goods_data, ['GoodsCode'], ['GoodsName', 'GoodsChenlie', 'GoodsStatus', 'CategoryCode', 'season_name', 'goods_img', 'SortCode', 'is_hot', 'price', 'brand_code','weight','unit_name']);
                        
                            promisePromotions['Pos_xiaopiao_templates'] = dbReplaceInto('Pos_xiaopiao_templates', xiaopiao_data, ['name', 'width', 'content', 'id', 'sys', 'lastchanged']);
                    
                            
                            
                            //dbReplace('Pos_xiaopiao_templates', xiaopiao_data, ['name'], ['lastchanged', 'sys', 'name', 'width', 'content']);
                            promisePromotions['Pos_stock_templates'] = dbReplaceInto('Pos_stock_templates', stock_data, ['name', 'width', 'content', 'id', 'sys', 'lastchanged']);
                    
                            
                            
                            //dbReplace('Pos_stock_templates', stock_data, ['name'], ['lastchanged', 'sys', 'name', 'width', 'content']);
                            promisePromotions['Pos_base_store'] = dbReplaceInto('Pos_base_store', store_data, ['store_code', 'store_name', 'store_id', 'store_property', 'status', 'pid']);
                    
                            
                            
                            //dbReplace('Pos_base_store', store_data, ['store_id'], ['store_code', 'store_name', 'store_property', 'status', 'pid']);
                            promisePromotions['PosSort'] = dbReplaceInto('PosSort', sort_data, ['sort_code', 'sort_name', 'is_fetch', 'p_code', 'is_show']);
                    
                            
                            //dbReplace('PosSort', sort_data, ['sort_code'], ['sort_name', 'is_fetch', 'p_code', 'is_show']);
                            promisePromotions['PosAssociatedGoods'] = dbReplaceInto('PosAssociatedGoods', AssociatedGoods_data, ['GoodsCode', 'Id', 'CollectionCode']);
                    
                            
                            //dbReplace('PosAssociatedGoods', AssociatedGoods_data, ['Id'], ['GoodsCode', 'CollectionCode']);

                            promisePromotions['Pos_skin_type'] = dbReplaceInto('Pos_skin_type', skin_data, ['skin_code', 'skin_name']);
                    
                            //dbReplace('Pos_skin_type', skin_data, ['skin_code'], ['skin_name']);
                            promisePromotions['PosPurview'] = dbReplaceInto('PosPurview', purview_data, ['role_purview_id', 'purview_id', 'role_id', 'name', 'url']);
                    
                            //dbReplace('PosPurview', purview_data, ['role_purview_id'], ['purview_id', 'role_id', 'name', 'url']);
                            console.log(reason_data);
                            promisePromotions['Pos_return_reason'] = dbReplaceInto('Pos_return_reason', reason_data, ['trade_type_code', 'trade_type_name', 'remark', 'return_reason_id', 'return_desc', 'sys']);
                    
                            //dbReplace('Pos_return_reason', reason_data, ['trade_type_code'], ['sys'], ['return_desc'], ['return_reason_id'], ['trade_type_name'], ['remark']);
                            return $q.all(promisePromotions);
                        }).then(function (success) {
                            dbTrans.commit();
                        }).catch(function (err) {
                            //baison_app.api.alert({msg:err,title:'err'});;
                            dbTrans.rollback();
                        });

                    }

                    return $q.all(promiseInstall);
                };
            }]);